<template>
  <el-dialog :title="title" custom-class="event-dialog" :close-on-click-modal="false" :modal="false"
    :visible.sync="open" :before-close="handleClose" width="780px">
    <el-scrollbar class="event-scrollbar" wrap-class="event-scrollbar__wrap">
      <el-form ref="form" :class="readonly ? 'detail' :'edit'" label-suffix=":" size="small" :rules="rules"
        :model="formData" hide-required-asterisk inline label-width="90px">
        <el-row type="flex">
          <el-col :span="14">
            <el-form-item label="事件名称" prop="eventName">
              <el-input v-model="formData.eventName" :readonly="readonly">
              </el-input>
            </el-form-item>
            <el-form-item label="事件等级" prop="eventType">
              <el-select v-model="formData.eventType" popper-class="default-select-popper" :disabled="disabled">
                <el-option v-for="opt in dict.eventTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="eventStatus">
              <el-select v-model="formData.eventStatus" popper-class="default-select-popper" :disabled="disabled">
                <el-option v-for="opt in dict.eventStatusOptions" :key="opt.value" :label="opt.label"
                  :value="opt.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上报人" prop="userName">
              <el-input v-model="formData.userName" disabled readonly></el-input>
            </el-form-item>
            <el-form-item label="联系号码" prop="userTel">
              <el-input v-model="formData.userTel" disabled readonly></el-input>
            </el-form-item>
            <el-form-item label="上报时间" prop="createTime">
              <el-date-picker v-model="formData.createTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" disabled
                readonly>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <div id="event-map" class="event-map"></div>
          </el-col>
        </el-row>
        <el-row class="remark">
          <el-form-item label="事件描述" prop="eventDescribe">
            <el-input type="textarea" :rows="3" v-model="formData.eventDescribe" :readonly="readonly">
            </el-input>
          </el-form-item>
        </el-row>
        <el-row class="remark">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="3" v-model="formData.remark" :readonly="readonly"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" v-show="formData.pocEventDetailList" @click="handleAttachment">附 件</el-button>
      <el-button @click="handleEdit(submitBtn)" :disabled="commitDisabled" size="small">{{ submitBtn ? '确 定' : '编 辑' }}
      </el-button>
      <el-button @click="handleClose" size="small">取 消</el-button>
    </div>
    <!-- 附件窗口 -->
    <el-dialog v-if='attachmentVisible' title="附件详情" :modal="false" custom-class="inner-dialog"
      :visible.sync="attachmentVisible">
      <svg-icon class="back-to-list" icon-class="back" @click="attachmentVisible = false"></svg-icon>

      <el-scrollbar class="event-scrollbar" wrap-class="event-scrollbar__wrap">
        <el-card v-for="item in formData.pocEventDetailList" :label="item.fileName" :key="item.detailId">
          <!-- 语音 -->
          <div v-if="item.fileType === 'audio'" class="attachment-carousel-item">
            <audio loop controls :src="item.fileAddr" @click.stop></audio>
          </div>
          <!-- 视频 -->
          <div v-else-if="item.fileType === 'video'" class="attachment-carousel-item">
            <video :src="item.fileAddr" controls='controls' loop @click.stop></video>
          </div>
          <!-- 图片 -->
          <div v-else-if="item.fileType === 'img'" class="attachment-carousel-item">
            <el-image :src="item.fileAddr"></el-image>
          </div>
          <div v-else class="attachment-carousel-item"> {{item.fileName}}</div>
        </el-card>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="download">下载当前附件</el-button>
        <el-button size="small" @click="downloadAll">下载所有附件</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { putObj, getFile } from '@/api/event'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import { msgError, msgSuccess } from '@/utils/message'
export default {
  props: {
    open: Boolean,
    title: String,
    formData: Object,
  },

  computed: {
    ...mapGetters(['dict']),
  },
  data() {
    return {
      readonly: true, // 详情时只读
      disabled: true,
      submitBtn: false,

      pocEventDetailList: [
        {
          detailId: 1,
          fileName: '11',
          fileType: 'img',
          fileAddr: require('@/assets/images/gis-event.png'),
        },
        {
          detailId: 2,
          fileName: '',
          fileType: 'img',
          fileAddr: require('@/assets/images/gis-event.png'),
        },
        {
          detailId: 3,
          fileName: '',
          fileType: 'img',
          fileAddr: require('@/assets/images/gis-event.png'),
        },
        {
          detailId: 4,
          fileName: '',
          fileType: 'img',
          fileAddr: require('@/assets/images/gis-event.png'),
        },
      ],

      rules: {
        eventName: [
          {
            required: true,
            message: '事件名称不能为空',
            trigger: 'blur',
          },
        ],
      },

      commitDisabled: false, // 提交按钮

      map: null, // 地图
      marker: null, // 标注

      attachmentVisible: false, // 打开附件窗口
      activeItem: null, //当前激活的文件
    }
  },
  methods: {
    // 下载当前附件
    download() {
      let activeItem = this.activeItem
        ? this.activeItem
        : this.formData.pocEventDetailList[0]
      let fileAddr = activeItem.fileAddr
      getFile(`${location.origin}${fileAddr}`).then((data) => {
        const file_name = fileAddr.substr(fileAddr.lastIndexOf('/') + 1) // 获取文件名
        FileSaver.saveAs(new Blob([data]), file_name) // 利用file-saver保存文件  自定义文件名
      })
    },
    // 下载所有附件
    downloadAll() {
      let fileList = this.formData.pocEventDetailList
      if (fileList == null || fileList.length == 0) {
        return this.msgError('没有可下载文件')
      }

      const zip = new JSZip()
      const promises = []
      fileList.forEach((item) => {
        const fileAddr = item.fileAddr
        const promise = getFile(`${location.origin}${fileAddr}`).then(
          (data) => {
            // 下载文件, 并存成ArrayBuffer对象
            const file_name = fileAddr.substr(fileAddr.lastIndexOf('/') + 1) // 获取文件名
            zip.file(file_name, data, { binary: true }) // 逐个添加文件
          }
        )
        promises.push(promise)
      })
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: 'blob' }).then((content) => {
          // 生成二进制流
          FileSaver.saveAs(content, '上报附件.zip') // 利用file-saver保存文件  自定义文件名
        })
      })
    },
    // 当前激活
    handleChange(index) {
      this.activeItem = this.formData.pocEventDetailList[index]
    },
    // 查看附件
    handleAttachment() {
      this.attachmentVisible = true
    },
    //编辑
    handleEdit(submitBtn) {
      if (!submitBtn) {
        this.readonly = false
        this.disabled = false
        this.submitBtn = true
        if (this.marker) {
          this.marker.enableDragging()
          this.marker.setLabel(
            new BMap.Label('请拖拽选择点位', {
              offset: new BMap.Size(20, -20),
            })
          )
        }
      } else {
        let form = this.formData
        let point = this.marker.getPosition()
        form.eventLongitude = point.lng
        form.eventLatitude = point.lat
        this.commitDisabled = true
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // 提交表单
            putObj(form)
              .then((res) => {
                if (res.code === 0) {
                  msgSuccess('编辑成功')
                  try {
                    this.$store.commit('updateEvent', { obj: form })
                  } catch (error) {}
                  this.handleClose()
                } else {
                  msgError('编辑失败')
                }
                this.commitDisabled = false
              })
              .catch((err) => {
                console.log(err)
                this.commitDisabled = false
                msgError('编辑失败')
              })
          } else {
            this.commitDisabled = false
          }
        })
      }
    },
    // 关闭或取消
    handleClose() {
      this.$emit('update:open', false)
    },
    // 初始化地图
    initBmap() {
      if (
        this.formData &&
        this.formData.eventLongitude &&
        this.formData.eventLatitude
      ) {
        let map = (this.map = new BMap.Map('event-map', {
          minZoom: 4,
          maxZoom: 19,
          enableMapClick: false,
        }))
        let center = new BMap.Point(
          this.formData.eventLongitude,
          this.formData.eventLatitude
        )
        map.centerAndZoom(center, 14) // 初始化地图,设置中心点坐标和地图级别。
        //map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] }));
        map.setMapType(BMAP_NORMAL_MAP)
        map.enableScrollWheelZoom() // 启用滚轮放大缩小

        map.clearOverlays()
        let marker = (this.marker = new BMap.Marker(center))
        map.addOverlay(marker)

        marker.addEventListener('click', (e) => {
          let position = e.target.getPosition()
          let content = `<div>${position.lng}</div><div>${position.lat}</div>`
          let label = new BMap.Label(content, {
            offset: new BMap.Size(20, -20),
          })
          marker.setLabel(label)
        })
        marker.addEventListener('dragging', (e) => {
          let content = `<div>${e.point.lng}</div><div>${e.point.lat}</div>`
          let label = new BMap.Label(content, {
            offset: new BMap.Size(20, -20),
          })
          marker.setLabel(label)
        })
        marker.addEventListener('dragend', (e) => {
          let content = `<div>${e.point.lng}</div><div>${e.point.lat}</div>`
          let label = new BMap.Label(content, {
            offset: new BMap.Size(20, -20),
          })
          marker.setLabel(label)
        })
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initBmap()
    })
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/event_dialog.scss';
</style>